import CryptoJS from 'crypto-js'

export const buildLoginVerifyInfo = (form, encryptInfo) => {
  let verifyInfo = {}
  let encryptUserStr = buildLoginEncryptUser(form, encryptInfo)

  verifyInfo.key = encryptInfo.encryptKey
  verifyInfo.string = encryptUserStr

  return verifyInfo
}

const buildLoginEncryptUser = (form, encryptInfo) => {
  let userDto = {}
  let pd = password2pd(form.password)

  userDto.pd1 = pd.pd1
  userDto.pd2 = pd.pd2
  // userDto.md5 = pd.md5;
  userDto.userName = form.username

  let encryptUserStr = encryptByDESModeCBC(encryptInfo.encryptString, JSON.stringify(userDto))
  return encryptUserStr
}

export const buildRegisteVerifyInfo = (form, encryptInfo) => {
  let verifyInfo = {}
  let encryptUserStr = buildRegistEncryptUser(form, encryptInfo)

  verifyInfo.key = encryptInfo.encryptKey
  verifyInfo.string = encryptUserStr
  verifyInfo.code = encryptByDESModeCBC(encryptInfo.encryptString, '888888')

  return verifyInfo
}

const buildRegistEncryptUser = (form, encryptInfo) => {
  let userDto = {}
  let pd = password2pd(form.password)

  userDto.pd1 = pd.pd1
  userDto.pd2 = pd.pd2
  userDto.md5 = pd.md5
  userDto.telNum = form.phoneNumber
  userDto.userName = form.username

  let encryptUserStr = encryptByDESModeCBC(encryptInfo.encryptString, JSON.stringify(userDto))
  return encryptUserStr
}

const password2pd = (password) => {
  let pd1 = ''

  let pd2 = ''
  let pd1ProStr = ''
  let pd = {}

  let md5Str = md5encode(password)

  let desMd5Str = encryptByDESModeCBC(md5Str, password)

  pd2 = Math.round(Math.random() * 10)

  for (let i = 0; i < pd2; i++) {
    let rand = Math.floor(Math.random() * desMd5Str.length)
    pd1ProStr += desMd5Str.charAt(rand)
  }

  pd1 = pd1ProStr.concat(desMd5Str)

  pd.pd1 = pd1
  pd.pd2 = pd2
  pd.md5 = md5Str

  return pd
}

const md5encode = (word) => {
  return CryptoJS.MD5(word).toString()
}

const encryptByDESModeCBC = (key, message) => {
  // let key = this.EncryptInfo.encryptString;
  let keyHex = CryptoJS.enc.Utf8.parse(key)
  let encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

